<template>
  <div class="apps container">
    <a-row :gutter="8">
      <!-- 应用总数统计 -->
      <a-col :span="6">
        <div class="panel">
          <div class="panel-title">应用总数</div>
          <div ref="appCountChartRef" class="chart-container"></div>
        </div>
      </a-col>
      
      <!-- Chart总数统计 -->
      <a-col :span="6">
        <div class="panel">
          <div class="panel-title">Chart总数</div>
          <div ref="chartCountChartRef" class="chart-container"></div>
        </div>
      </a-col>
      
      <!-- 项目Chart数量统计柱状图 -->
      <a-col :span="12">
        <div class="panel">
          <div class="panel-title">项目Chart统计</div>
          <div ref="projectChartRef" class="chart-container"></div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { invoke } from "@tauri-apps/api/core";
import { Notification } from '@arco-design/web-vue';
import { App } from '@/model/App.ts';
// echarts 按需导入，减小 bundle 大小
import * as echarts from 'echarts/core';
import { GaugeChart, BarChart } from 'echarts/charts';
import { SVGRenderer } from 'echarts/renderers';
import { TooltipComponent, GridComponent } from 'echarts/components';
import type { EChartsOption } from 'echarts';
// 注册必要的组件和渲染器
echarts.use([GaugeChart, BarChart, SVGRenderer, TooltipComponent, GridComponent]);

// 图表实例引用
const appCountChartRef = ref<HTMLElement>();
const chartCountChartRef = ref<HTMLElement>();
const projectChartRef = ref<HTMLElement>();

let appCountChart: echarts.ECharts | null = null;
let chartCountChart: echarts.ECharts | null = null;
let projectChart: echarts.ECharts | null = null;

// 统计数据
const totalApps = ref(0);
const totalCharts = ref(0);
const projectChartData = ref<Array<{ name: string; count: number }>>([]); // 项目Chart统计数据

/**
 * @function getThemeColors
 * @description 获取当前主题色系
 */
const getThemeColors = () => {
  const root = document.documentElement;
  const computedStyle = getComputedStyle(root);
  
  // 将颜色转换为 rgba 格式以支持透明度
  const addAlpha = (color: string, alpha: number = 0.8) => {
    // 如果是 hex 颜色，转换为 rgb
    if (color.startsWith('#')) {
      const r = parseInt(color.slice(1, 3), 16);
      const g = parseInt(color.slice(3, 5), 16);
      const b = parseInt(color.slice(5, 7), 16);
      return `rgba(${r}, ${g}, ${b}, ${alpha})`;
    }
    // 如果是 rgb 格式，转换为 rgba
    if (color.startsWith('rgb(')) {
      return color.replace('rgb(', 'rgba(').replace(')', `, ${alpha})`);
    }
    // 如果已经是 rgba，返回原值
    return color;
  };
  
  const primary = computedStyle.getPropertyValue('--theme-6').trim() || '#722ED1';
  
  return {
    primary: addAlpha(primary, 0.75),
    primarySolid: primary,
    textColor: '#a0a0a0',
    splitLine: '#2a2a2a',
    bgColor: 'rgba(0, 0, 0, 0.8)'
  };
};

/**
 * @function initAppCountChart
 * @description 初始化应用总数统计图
 */
const initAppCountChart = () => {
  if (!appCountChartRef.value) return;
  
  if (!appCountChart) {
    appCountChart = echarts.init(appCountChartRef.value, null, { renderer: 'svg' });
  }
  
  const colors = getThemeColors();
  
  const option: EChartsOption = {
    tooltip: {
      formatter: '{c}'
    },
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: Math.max(totalApps.value * 2, 10),
        splitNumber: 5,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: colors.primary.replace('0.75', '0.2') },
            { offset: 1, color: colors.primary.replace('0.75', '0.6') }
          ])
        },
        progress: {
          show: true,
          width: 18,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: colors.primary.replace('0.75', '0.2') },
              { offset: 1, color: colors.primary.replace('0.75', '0.6') }
            ])
          }
        },
        pointer: {
          show: false
        },
        axisLine: {
          lineStyle: {
            width: 18,
            color: [[1, colors.splitLine]]
          }
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          show: false
        },
        anchor: {
          show: false
        },
        title: {
          show: false
        },
        detail: {
          valueAnimation: true,
          fontSize: 36,
          fontWeight: 'bold',
          offsetCenter: [0, '10%'],
          color: colors.primary,
          formatter: '{value}'
        },
        data: [
          {
            value: totalApps.value
          }
        ]
      }
    ]
  };
  
  appCountChart.setOption(option);
};

/**
 * @function initChartCountChart
 * @description 初始化Chart总数统计图
 */
const initChartCountChart = () => {
  if (!chartCountChartRef.value) return;
  
  if (!chartCountChart) {
    chartCountChart = echarts.init(chartCountChartRef.value, null, { renderer: 'svg' });
  }
  
  const colors = getThemeColors();
  
  const option: EChartsOption = {
    tooltip: {
      formatter: '{c}'
    },
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: Math.max(totalCharts.value * 2, 10),
        splitNumber: 5,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: colors.primary.replace('0.75', '0.2') },
            { offset: 1, color: colors.primary.replace('0.75', '0.6') }
          ])
        },
        progress: {
          show: true,
          width: 18,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: colors.primary.replace('0.75', '0.2') },
              { offset: 1, color: colors.primary.replace('0.75', '0.6') }
            ])
          }
        },
        pointer: {
          show: false
        },
        axisLine: {
          lineStyle: {
            width: 18,
            color: [[1, colors.splitLine]]
          }
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          show: false
        },
        anchor: {
          show: false
        },
        title: {
          show: false
        },
        detail: {
          valueAnimation: true,
          fontSize: 36,
          fontWeight: 'bold',
          offsetCenter: [0, '10%'],
          color: colors.primary,
          formatter: '{value}'
        },
        data: [
          {
            value: totalCharts.value
          }
        ]
      }
    ]
  };
  
  chartCountChart.setOption(option);
};

/**
 * @function initProjectChart
 * @description 初始化项目Chart统计柱状图
 */
const initProjectChart = () => {
  if (!projectChartRef.value) return;
  
  if (!projectChart) {
    projectChart = echarts.init(projectChartRef.value, null, { renderer: 'svg' });
  }
  
  const colors = getThemeColors();
  
  const projectNames = projectChartData.value.map(item => item.name);
  const chartCounts = projectChartData.value.map(item => item.count);
  
  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      backgroundColor: colors.bgColor,
      borderColor: colors.primarySolid,
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '8%',
      top: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: projectNames,
      axisLine: {
        lineStyle: {
          color: colors.primarySolid
        }
      },
      axisLabel: {
        color: colors.textColor,
        interval: 0,
        rotate: projectNames.length > 5 ? 45 : 0,
        fontSize: 12,
        fontWeight: 'normal'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: colors.primarySolid
        }
      },
      axisLabel: {
        color: colors.textColor
      },
      splitLine: {
        lineStyle: {
          color: colors.splitLine
        }
      }
    },
    series: [
      {
        name: 'Chart数量',
        type: 'bar',
        data: chartCounts.map((value) => ({
          value,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              { offset: 0, color: colors.primary.replace('0.75', '0.15') },
              { offset: 1, color: colors.primary.replace('0.75', '0.5') }
            ])
          }
        })),
        barWidth: '50%',
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: colors.primary
          }
        }
      }
    ]
  };
  
  projectChart.setOption(option);
};

/**
 * @function updateChartsTheme
 * @description 更新所有图表的主题色
 */
const updateChartsTheme = () => {
  initAppCountChart();
  initChartCountChart();
  initProjectChart();
};

/**
 * @function handleThemeChange
 * @description 监听主题变化
 */
const handleThemeChange = () => {
  // 使用 MutationObserver 监听 class 变化
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.attributeName === 'class') {
        // 延迟一点时间确保 CSS 变量已更新
        setTimeout(() => {
          updateChartsTheme();
        }, 50);
      }
    });
  });
  
  observer.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ['class']
  });
  
  return observer;
};

/**
 * @function loadStatistics
 * @description 加载统计数据
 */
const loadStatistics = async () => {
  try {
    // 获取应用总数
    const apps = await invoke<Array<App>>("get_apps");
    totalApps.value = apps.length;
    
    // 统计所有应用的Chart总数和各项目的Chart数量
    let chartCount = 0;
    const projectData: Array<{ name: string; count: number }> = [];
    
    for (const app of apps) {
      try {
        const response = await invoke("get_charts", { url: app.url + "/api/charts" });
        // 将HashMap转换为数组并统计Chart数量
        const chartMap = response as Record<string, Array<any>>;
        const appChartCount = Object.keys(chartMap).length;
        chartCount += appChartCount;
        
        // 记录每个项目的Chart数量
        projectData.push({
          name: app.name,
          count: appChartCount
        });
      } catch (error) {
        console.warn(`获取应用 ${app.name} 的Charts失败:`, error);
        // 如果某个应用获取失败，记录为0
        projectData.push({
          name: app.name,
          count: 0
        });
      }
    }
    
    totalCharts.value = chartCount;
    projectChartData.value = projectData;
    
    // 初始化图表
    initAppCountChart();
    initChartCountChart();
    initProjectChart();
  } catch (err) {
    console.error(err);
    Notification.error({ content: '加载统计数据失败' });
  }
};

/**
 * @function handleResize
 * @description 处理窗口大小变化
 */
const handleResize = () => {
  appCountChart?.resize();
  chartCountChart?.resize();
  projectChart?.resize();
};

let themeObserver: MutationObserver | null = null;

/**
 * @function onMounted
 * @description 组件挂载时加载统计数据
 */
onMounted(async () => {
  await loadStatistics();
  window.addEventListener('resize', handleResize);
  themeObserver = handleThemeChange();
});

/**
 * @function onUnmounted
 * @description 组件卸载时清理资源
 */
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  themeObserver?.disconnect();
  appCountChart?.dispose();
  chartCountChart?.dispose();
  projectChart?.dispose();
});
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  box-sizing: border-box;
  padding: 8px;
  overflow-y: auto;
  
  .arco-row {
    margin-bottom: 0 !important;
    
    & + .arco-row {
      margin-top: 8px;
    }
  }
}

.panel {
  height: 265px;
  background-color: rgba(35, 35, 36, 0.5);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  padding: 8px;
  transition: all 0.3s;
  
  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .panel-title {
    font-size: 16px;
    font-weight: bold;
    color: var(--theme-primary);
    margin-bottom: 8px;
    padding-bottom: 6px;
    border-bottom: 1px solid var(--theme-primary);
  }

  .chart-container {
    flex: 1;
    width: 100%;
    min-height: 0;
  }
}
</style>
